# encoding: utf-8
"""
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    created by siyi.chen on '10/10/2024'
    comment: 根据相关知识进行QA问答，生成回复
"""
import asyncio
from project.model.basic import User, Knowledge
from project.service.agents.agent import Agent
from project.model.flow import Flow
from project.service.knowledge import KnowledgeService


class NlgService:

    @staticmethod
    async def nlg(user: User, user_message,
                  knowledge: Knowledge,
                  chat_model_name='',
                  agent_profile = '',
                  user_role='',
                  flows: list[Flow]=None,
                  session=None):
        """
        :param user
        :param user_message:
        :param knowledge:
        :param chat_model_name:
        :param agent_profile:
        :param user_role:
        :param flows:
        :return:
        """
        services = [v.service_agent_desc() for v in flows or []]

        # 掌握的知识库
        # related_knowledge = KnowledgeService.retrieve(session, user_message, knowledge.key if knowledge else '')
        data = await KnowledgeService.get_knowledge_match_list(session, user_message, organization_code=knowledge.key if knowledge else '')
        related_knowledge = [v['text'] for v in data]

        instruction = """
        ###Instruction
        {agent_profile}，你服务于房间中的{user_role}。请结合你掌握的背景知识以及你和{user_role}的对话历史，回复{user_role}的对话，注意请尽量简短回复，控制内容在100个字以内。

        你们的对话历史：{user_memories}

        针对这段对话你所掌握的背景知识为：{related_knowledge}
        
        你可以提供的服务：{services}

        ###Output
        你会对{user_role}说：
        """
        agent = Agent(user, user_message, chat_model_name=chat_model_name, business_name="nlg聊天", agent_profile=agent_profile, user_role=user_role)
        response = await agent.async_interact(prompt=instruction, related_knowledge=related_knowledge, services=services)
        if not response:
            return None
        # 后处理
        response = response.replace(':', '：').replace(f'我会对{user_role}说：', '').replace(f'你会对{user_role}说：', '')
        return {'intent': 'chat', 'action': 'chat', 'response': response}


if __name__ == "__main__":

    user = User()
    user_message = "酒店有没有提供可以专门办公的地方"
    print(f'住客对你说：{user_message}')
    result = asyncio.run(NlgService.nlg(user, user_message))
    print(f'你对住客说：{result}')

